﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace cs499.Database
{
    public partial class Schedule
    {
        public bool Delete()
        {
            bool retval = true;
            Model1Container db = new Model1Container();
            Schedule schedule = db.Set<Schedule>()
                .Include("ScheduledCourses")
                .Include("ScheduledCourses.TaughtBy")
                .Include("ScheduledCourses.Course")
                .Include("ScheduledCourses.Room")
                .Include("ScheduledCourses.TimeSlot")
                .Include("ConflictedCourses")
                .Include("ConflictedCourses.TaughtBy")
                .Include("ConflictedCourses.Course")
                .Include("ConflictedCourses.Room")
                .Include("ConflictedCourses.TimeSlot")
                .Include("Department")
                .FirstOrDefault(sch => sch.Id == this.Id);

            foreach (CourseInstance ci in schedule.ScheduledCourses.ToList())
            {
                db.Set<CourseInstance>().Remove(ci);
            }
            foreach (CourseInstance ci in schedule.ConflictedCourses.ToList())
            {
                db.Set<CourseInstance>().Remove(ci);
            }
            try
            {
                db.Set<Schedule>().Remove(schedule);
                db.SaveChanges();
                retval = true;
            }
            catch (Exception /**/)
            {
                return false;
            }
            return retval;
        }

        public override String ToString()
        {
            String result = "Conflicted:<br>";

            foreach (CourseInstance instance in this.ConflictedCourses)
            {
                result = result +
                    instance.Course.CourseTitle + "    " +
                    instance.SectionNumber + "<br>";
            }

            result = result + "<br>Scheduled:<br>";

            foreach (CourseInstance instance in this.ScheduledCourses)
            {
                try
                {
                    result = result +
                    instance.Course.CourseTitle + "    " +
                    instance.SectionNumber + "    " +
                    instance.Room.PlaceName + "    " +
                    instance.TimeSlot.ToString() + "    " +
                    instance.TaughtBy + "<br />";
                }
                catch (Exception)
                {

                }
            }

            return result;
        }


        public static List<Room> GetAvailableRooms(Int32 courseid)
        {
            List<Room> retlist = new List<Room>();
            Model1Container db = new Model1Container();
            Course course = db.Set<Course>()
                .Include("PlaceRequirements")
                .Include("CourseInstances")
                .FirstOrDefault(c => c.Id == courseid);
            if (course == null) return retlist;
            if (course.PlaceRequirements.Count > 0)
            {
                if (course.PlaceRequirements.OfType<Room>().ToList().Count == 0)
                {
                    foreach (Building _building in course.PlaceRequirements.OfType<Building>().ToList())
                    {
                        Building dbbuilding = db.Set<Building>().Include("Rooms").FirstOrDefault(build => build.Id == _building.Id);

                        foreach (Room temproom in dbbuilding.Rooms)
                        {
                                retlist.Add(temproom);
                        }
                    }
                }
                else
                {
                    foreach (Room temproom in course.PlaceRequirements.OfType<Room>().ToList())
                    {
                            retlist.Add(temproom);
                    }
                }
            }
            else
            {
                List<Room> departmentrooms = db.Set<Room>().Where(rm => rm.DepartmentId == course.DepartmentId).ToList();
                foreach (Room temproom in departmentrooms)
                {
                        retlist.Add(temproom);
                }
            }
            return retlist;
        }

        public static List<TimeSlot> GetAvailableTimeSlots(int roomid, int facultyid)//if facultyid == -1 use current loggedin facultymember
        {//returns list of time slots during which current faculty member is not busy and room is not busy
            List<TimeSlot> retlist = new List<TimeSlot>();
            Model1Container db = new Model1Container();
            Room inroom = db.Set<Room>()
                .Include("CourseInstances")
                .Include("CourseInstances.TaughtBy")//for scheduling add additional include for taughtby
                .Include("CourseInstances.PreferredBy")
                .Include("CourseInstances.Schedule")
                .Include("CourseInstances.TimeSlot")
                .FirstOrDefault(rm => rm.Id == roomid);
            if (inroom == null) return retlist;
            List<TimeSlot> timeslots = db.Set<TimeSlot>()
                .Include("CourseInstances").ToList();

            bool isvalid = true;
            foreach (TimeSlot timetovalidate in timeslots)
            {
                isvalid = true;
                foreach (CourseInstance ci in inroom.CourseInstances)
                {
                    if (ci.Schedule == null || ci.PreferredBy != null) continue;//true if it is a preference  //for scheduling change continue to logic and add else which continues

                    if (timetovalidate.OverlapsWith(ci.TimeSlot))
                    {
                        isvalid = false;
                        break;
                    }
                }
                if (isvalid)
                {
                    if (facultyid == -1)//use current user
                    {
                        MembershipUser tempuser = Membership.GetUser(HttpContext.Current.User.Identity.Name);
                        Database.Faculty currentfaculty;
                        if (HttpContext.Current.Session["CurrentDepartmentId"] != null)
                        {
                            int CurrentDepartmentId = (int)HttpContext.Current.Session["CurrentDepartmentId"];
                            Department CurrentDepartment = ListOfDepartment.GetDepartment(ID: CurrentDepartmentId);
                            currentfaculty = CurrentDepartment.GetFaculty((Guid)tempuser.ProviderUserKey);
                            if (currentfaculty != null) facultyid = currentfaculty.Id;
                        }
                    }
                    cs499.Database.Faculty faculty = db.Set<Faculty>()
                        .Include("CourseInstances")//for scheduling change to CourseInstances
                        .Include("CourseInstances.TimeSlot")
                        .FirstOrDefault(fac => fac.Id == facultyid);
                    if (faculty != null)
                    {//on error skip faculty check
                        foreach (CourseInstance ci in faculty.CourseInstances)
                        {
                            if (timetovalidate.OverlapsWith(ci.TimeSlot))
                            {
                                isvalid = false;
                                break;
                            }
                        }
                    }
                    if (isvalid)
                    {
                        retlist.Add(timetovalidate);
                    }
                }
            }

            return retlist;
        }
    }
}